package com.mskj.zxmy.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.mskj.zxmy.common.Md5Util;
import com.mskj.zxmy.common.Result;
import com.mskj.zxmy.dto.UserDTO;
import com.mskj.zxmy.entity.User;
import com.mskj.zxmy.mapper.StockInMapper;
import com.mskj.zxmy.mapper.UserMapper;
import com.mskj.zxmy.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@Tag(name = "登录", description = "登录")
@CrossOrigin
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private StockInMapper stockInMapper;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @Operation(description = "账号密码登录")
    public Result login(@RequestBody UserDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        //判断该用户是否存在
        if (loginUser == null) {
            return Result.failed("登录用户不存在");
        }
        String pwd = loginUser.getPassword();
        String str = pwd.split("#")[0];
        String str1 = pwd.split("#")[1];
        String passwordMd5 = Md5Util.getMD5String(password);
        String digest = Md5Util.getMD5String(passwordMd5 + str1);
        if (!str.equals(digest)) {
            return Result.failed("账号密码错误");
        }

        String userId = loginUser.getUserId();
        String memberId = userMapper.findByMemberId(userId);
        StpUtil.login(memberId);
        String token = StpUtil.getTokenValue();
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("nick", stockInMapper.getUserName((String) StpUtil.getLoginId()));
        //判断密码是否正确
        return Result.success(map);
    }

}
